const api = require('../../api/api.js');

Page({
  data: {
    localImgSrc: '',
    categoryArr: ['商品', '土壤'],
    categoryTypeArr: ['good', 'soil'],
    categoryArrIndex: 0,
    objArr: [],
    objIdArr: [],
    objArrIndex: 0,
    entArr: [],
    entIdArr: [],
    currentIndex: 0,
    goods:[]
  },
  onLoad(o) {
    let that = this;
    let id = o.id;
    wx.getStorage({
      key: 'userId',
      success(e) {
        console.log(e);
        that.setData({
          userId: e.data,
          id
        });
      }
    })
    wx.getStorage({
      key: 'role',
      success(res) {
        that.setData({
          role: res.data
        })
        const role = res.data
        if (role === 0) {
          that.getEntAdmin()
        } else {
          that.getEnt()
        }
      }
    })
  },
  getEntAdmin() {
    let that = this
    api.getAllEnterprise({
      data: {
        page: -1,
        limit: -1
      },
      success(response) {
        that.formatEntData(response.data)
      }
    })
  },
  getEnt() {
    let that = this
    if (that.data.role === 4) {
      wx.getStorage({
        key: 'userId',
        success(res) {
          api.queryEnterprise({
            data: {
              account: res.data,
              page: -1,
              limit: -1
            },
            success(response) {
              that.formatEntData(response.data)
            }
          })
        }
      })
    } else {
      wx.getStorage({
        key: 'userId',
        success(res) {
          api.queryPlantation({
            data: {
              account: res.data
            },
            success(response) {
              that.formatEntData(response.data)
            }
          })
        }
      })
    }
  },
  formatEntData(data) {
    let that = this
    let entArr = []
    let entIdArr = []
    data.enterprise.map(item => {
      entArr.push(item.entName)
      entIdArr.push(item.entId)
    })
    if (entArr.length === 0) {
      entArr = ['无所属企业！'];
      entIdArr = [-1];
    }
    that.setData({
      entArr,
      entIdArr
    })
    let goods = []
    that.getGood(0, goods);
  },
  handleChange(e) {
    this.setData({
      currentIndex: Number.parseInt(e.detail.value)
    });
  },
  getGood(count, goods) {
    let that = this
    if (count === that.data.entIdArr.length) {
      let objArr = [];
      let objIdArr = [];
      if (goods.length === 0) {
        objArr = ['请先添加商品！'];
        objIdArr = [-1];
      } else {
        objArr = goods.map(i => {
          return i.name;
        });
        objIdArr = goods.map(i => {
          return i.id;
        });
      }
      that.setData({
        objArr,
        objIdArr,
        goods
      });
      return
    }
    api.queryGood_entId({
      data: {
        entId: that.data.entIdArr[count]
      },
      success(res) {
        // res.data.good.map((i) => {
        //   i.img = that.data.imgUrl + i.img
        // })
        goods.push(...res.data.good)
        that.getGood(++count, goods)
      }
    })
  },
  querySite() {
    let that = this;
    let userId = that.data.userId;
    api.queryPlantation({
      data: {
        account: userId
      },
      success(res) {
        console.log(res.data);
        let site = res.data.plantation;
        let objArr = [];
        let objIdArr = [];
        if (site.length === 0) {
          objArr = ['请先添加地块！'];
          objIdArr = [-1];
        } else {
          objArr = site.map(i => {
            return i.siteName;
          });
          objIdArr = site.map(i => {
            return i.siteId;
          });
        }
        that.setData({
          objArr,
          objIdArr
        });
      }
    });
  },
  formSubmit(e) {
    let that = this;
    let category = that.data.categoryTypeArr[that.data.categoryArrIndex];
    let objId = that.data.objIdArr[that.data.objArrIndex];
    let name = e.detail.value.name.trim();
    let userId = that.data.userId;
    let entId = that.data.entIdArr[that.data.currentIndex];
    let imgUrl = that.data.localImgSrc;
    if (name === '') {
      wx.showToast({
        title: '请将信息填写完整！',
        icon: 'none'
      })
      return;
    }
    if (objId === -1) {
      wx.showToast({
        title: '请先完善证书对象！',
        icon: 'none'
      })
      return;
    }
    if (imgUrl === '') {
      wx.showToast({
        title: '请选择图片！',
        icon: 'none'
      })
      return;
    }
    wx.showLoading({
      title: '提交中...',
    });
    api.addFile({
      data: {
        userId: userId,
        path: 'certificationImage',
        filePath: imgUrl
      },
      success(res) {
        let image = JSON.parse(res.data).fileName;
        api.addCertification({
          data: {
            certificationName: name,
            objId,
            category,
            image,
            entId,
            account: userId
          },
          success(res) {
            if (res.data === true) {
              let pages = getCurrentPages();
              let prePage = pages[pages.length - 2];
              prePage.onLoad();
              that.formitSuccess();
            }
          }
        });
      }
    });
  },
  formitSuccess() {
    wx.hideLoading();
    wx.showToast({
      title: '提交成功！',
    });
    wx.navigateBack({
      delta: '-1'
    });
  },
  pickimg(e) {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          localImgSrc: res.tempFilePaths[0]
        });
      }
    })
  },
  delimg() {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定取消选中的图片吗？',
      success(e) {
        if (e.confirm) {
          that.setData({
            localImgSrc: ''
          });
        }
      }
    })
  },
  bindCategoryTypeChange(e) {
    let that = this;
    let index = that.data.categoryArrIndex;
    this.setData({
      categoryArrIndex: Number.parseInt(e.detail.value)
    });
    if (index !== that.data.categoryArrIndex) {
      let type = that.data.categoryTypeArr[that.data.categoryArrIndex];
      switch (type) {
        case 'good':{
          let goods = that.data.goods
          let objArr = [];
          let objIdArr = [];
          if (goods.length === 0) {
            objArr = ['请先添加商品！'];
            objIdArr = [-1];
          } else {
            objArr = goods.map(i => {
              return i.name;
            });
            objIdArr = goods.map(i => {
              return i.id;
            });
          }
          that.setData({
            objArr,
            objIdArr,
            goods
          });
        }
          break;
        case 'soil':
          that.querySite();
          break;
      }
      that.setData({
        objArrIndex: 0
      });
    }
  },
  bindObjChange(e) {
    this.setData({
      objArrIndex: Number.parseInt(e.detail.value)
    });
  }
})